package com.mier.android.fbtalksms;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebook.model.GraphObject;
import com.mier.android.fbtalksms.adapter.FBFriends;
import com.mier.android.fbtalksms.adapter.SMSMessage;

import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.PhoneLookup;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("ShowToast")
public class MainActivity extends Activity {

	private static String App_Id = "196742477082115";
	private Facebook facebook = new Facebook(App_Id);
	private AsyncFacebookRunner mrunner;
	private String FILE_NAME = "SMSFacebook";
	private SharedPreferences mPrefs;

	private final String TAG = MainActivity.class.getCanonicalName();
	List<SMSMessage> message = new ArrayList<SMSMessage>();
	private List<FBFriends> fbfriends;
	private List<Integer> threadId = new ArrayList<Integer>();
	private List<String> contactIdList = new ArrayList<String>();
	private Date today;
	private DateFormat format = new SimpleDateFormat("h:mma MMM/d/yyyy");

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mrunner = new AsyncFacebookRunner(facebook);
		populateMessage();
		populateMessageList();
		ListView listView = (ListView) findViewById(R.id.listView);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long id) {
				Log.d(TAG, "finally!");
				// Toast.makeText(getBaseContext(), position + " : " + id,
				// Toast.LENGTH_SHORT).show();
				int thread_id = message.get(position).getThreadId();

			}
		});

	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	public void populateMessage() {
		message = retrieveInbox();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.connectFacebook:
//			loginToFacebook();
			Intent intent = new Intent(MainActivity.this, FBFriendsListActivity.class);
			startActivity(intent);
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void populateMessageList() {
		ListView listView = (ListView) findViewById(R.id.listView);
		ArrayAdapter<SMSMessage> adapter = new MessageListAdapter();
		listView.setAdapter(adapter);

	}
	
	public void populateFBFriendsList(){
		ListView view1 = (ListView) findViewById(R.id.listView);
		view1.setVisibility(View.INVISIBLE);
		Log.i(TAG, "List of Friends Successfully Populated");
		ListView viewList = (ListView) findViewById(R.id.fbListView);
		ArrayAdapter<FBFriends> fbAdapter = new FbFriendsAdapter();
		viewList.setAdapter(fbAdapter);
		
	}

	// function to login to facebook
	@SuppressWarnings("deprecation")
	public void loginToFacebook() {
		mPrefs = getPreferences(MODE_PRIVATE);
		String access_token = mPrefs.getString("access_token", null);
		long expires = mPrefs.getLong("access_expires", 0);

		if (access_token != null) {
			facebook.setAccessToken(access_token);
		}
		if (expires != 0) {
			facebook.setAccessExpires(expires);
		}
		if (!facebook.isSessionValid()) {
			facebook.authorize(this, new String[] { "email", "publish_stream",
					"user_status", "user_online_presence",
					"friends_online_presence" }, new DialogListener() {

				@Override
				public void onFacebookError(FacebookError e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onError(DialogError e) {
					// TODO Auto-generated method stub

				}

				@Override
				public void onComplete(Bundle values) {
					String fql = "SELECT name,uid FROM user WHERE online_presence IN ('active', 'idle') AND uid IN ( SELECT uid2 FROM friend WHERE uid1 = me())";
					values.putString("q", fql);
					Session session = Session.getActiveSession();
					Request request = new Request(session, "/fql", values,
							HttpMethod.GET, new Request.Callback() {

								@Override
								public void onCompleted(Response response) {
									GraphObject go = response.getGraphObject();
									JSONObject json;
									try {
										json = go.getInnerJSONObject();
										JSONArray jArray = json
												.optJSONArray("data");
										FBFriends friends;
										for (int i = 0; i < jArray.length(); i++) {
											friends = new FBFriends();
											friends.setFbId(jArray.getString(i));
											friends.setName(jArray.getString(i));
											friends.setFbProfile(getUserPic(jArray.getString(i)));
					                        fbfriends.add(friends);
										}
										populateFBFriendsList();
									} catch (FacebookError e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}

								}
							});

				}

				@Override
				public void onCancel() {
					// TODO Auto-generated method stub

				}
			});
		}
	}

	public class MessageListAdapter extends ArrayAdapter<SMSMessage> {
		public MessageListAdapter() {
			super(MainActivity.this, R.layout.message_list, message);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return message.size();
		}

		@Override
		public SMSMessage getItem(int position) {
			// TODO Auto-generated method stub
			return message.get(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View itemView = convertView;
			if (itemView == null) {
				itemView = getLayoutInflater().inflate(R.layout.message_list,
						parent, false);
			}

			TextView sender = (TextView) itemView
					.findViewById(R.id.sender_name);
			TextView body = (TextView) itemView.findViewById(R.id.msg_txt);
			TextView date = (TextView) itemView.findViewById(R.id.date_sent);
			sender.setText(message.get(position).getAddress());
			body.setText(message.get(position).getBody());
			date.setText(message.get(position).getDate());

			return itemView;
		}

	}
	
	
	public class FbFriendsAdapter extends ArrayAdapter<FBFriends>{

		public FbFriendsAdapter() {
			super(MainActivity.this, R.layout.fbfriends_list, fbfriends);
			// TODO Auto-generated constructor stub
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return fbfriends.size();
		}

		@Override
		public FBFriends getItem(int position) {
			// TODO Auto-generated method stub
			return fbfriends.get(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View listView = convertView;
			if (listView == null) {
				listView = getLayoutInflater().inflate(R.layout.fbfriends_list,
						parent, false);
			}

			TextView name = (TextView) listView
					.findViewById(R.id.fbName);
			name.setText(fbfriends.get(position).getName());
			ImageView profile = (ImageView) listView.findViewById(R.id.fbProfile);
			profile.setImageBitmap(fbfriends.get(position).getFbProfile());

			return listView;
		}
		
	}

	// return the bitmap for fb profile picture.
	public Bitmap getUserPic(String userID) {
		String imageURL;
		Bitmap bitmap = null;
		Log.d(TAG, "Loading Picture");
		imageURL = "http://graph.facebook.com/" + userID
				+ "/picture?type=small";
		try {
			bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageURL)
					.getContent());
		} catch (Exception e) {
			Log.d("TAG", "Loading Picture FAILED");
			e.printStackTrace();
		}
		return bitmap;
	}

	@SuppressWarnings("deprecation")
	public List<SMSMessage> retrieveInbox() {
		List<SMSMessage> messageList = new ArrayList<SMSMessage>();
		Uri uriConversation = Uri
				.parse("content://mms-sms/conversations?simple=true");
		Cursor cursor = this.getContentResolver().query(uriConversation, null,
				null, null, "normalized_date DESC");
		if (cursor != null) {
			cursor.moveToFirst();
			if (cursor.getCount() > 0) {
				do {

					// String columnNames[] = cursor.getColumnNames();
					// for (int i = 0; i < columnNames.length; i++) {
					// Log.d(TAG, columnNames[i]);
					// System.out.println(columnNames[i]);
					// }
					String id = cursor.getString(cursor.getColumnIndex("_id"));
					String body = cursor.getString(cursor
							.getColumnIndexOrThrow("snippet"));
					today = new Date(cursor.getLong(cursor
							.getColumnIndexOrThrow("date")));

					String date = format.format(today);
					String contactName = null;
					SMSMessage sms = new SMSMessage();
					Uri uriSms = Uri.parse("content://sms");
					String condition = "thread_id=" + id;
					Cursor c = this.getContentResolver().query(uriSms, null,
							condition, null, null);
					if (c.moveToFirst()) {
						String address = c.getString(c
								.getColumnIndexOrThrow("address"));
						contactName = getContactNameByNumber(address);
					}
					if (c != null) {
						c.close();
					}
					sms.setAddress(contactName);
					sms.setThreadId(Integer.parseInt(id));
					sms.setBody(body);
					sms.setDate(date);
					messageList.add(sms);
					threadId.add(Integer.parseInt(id));
					Log.d(TAG, "" + cursor.getColumnCount());
					Log.d(TAG, "" + cursor.getColumnName(0));
					Log.d(TAG, "" + cursor.getColumnName(1));
					Log.d(TAG, "" + cursor.getColumnName(2));

				} while (cursor.moveToNext());

			}

			if (cursor != null) {
				cursor.close();
			}
			return messageList;
		}
		return null;
	}

	public String getContactNameByNumber(String number) {
		String contactSMS = null;
		Uri uriContact = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
				Uri.encode(number));
		Cursor contactCursor = this.getContentResolver().query(uriContact,
				new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
				null, null, null);
		if (contactCursor.moveToFirst()) {
			int index = contactCursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
			String contactId = contactCursor.getString(contactCursor
					.getColumnIndex(PhoneLookup._ID));
			contactSMS = contactCursor.getString(index);
			contactIdList.add(contactId);
		}
		if (contactSMS == null) {
			contactSMS = number;
		}
		if (contactCursor != null) {
			contactCursor.close();
		}
		return contactSMS;
	}

	// public Bitmap getContactPhotoUri(long contactId){
	// Uri uriPhoto = ContentUris.withAppendedId(Contacts.CONTENT_URI,
	// contactId);
	// InputStream is =
	// ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(),
	// uriPhoto);
	//
	// if(is!= null){
	// return BitmapFactory.decodeStream(is);
	// }
	// return null;
	// }

}
